<template>
  <el-card>
    <el-row :gutter="20" class="header">
      <el-col :span="6">
        <el-input placeholder="请输入预约人姓名" clearable v-model="queryForm.query" />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" style="width: 100%" v-loading="loading">
      <el-table-column prop="client_name" label="预约人" width="180" />
      <el-table-column prop="counselor_name" label="咨询师" width="180" />
      <el-table-column prop="request_time" label="预约时间" width="250">
      <template #default="{ row }">
          {{ formatDateTime(row.request_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="appointment_status" label="状态" width="180">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.appointment_status)">
            {{ getStatusLabel(row.appointment_status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button
            type="warning"
            size="small"
            :icon="CircleCheck"
            @click="handleComplete(row)"
            v-if="row.appointment_status === 1"
          />
          <el-button
            type="danger"
            size="small"
            :icon="Close"
            @click="handleCancel(row)"
            v-if="row.appointment_status !== 2 && row.appointment_status !== 6"
          />
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="handleDelete(row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="queryForm.pagenum"
      v-model:page-size="queryForm.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Close, CircleCheck, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import appointmentApi from '@/api/appointment'
import clientApi from '@/api/client'
import counselorApi from '@/api/counselor'

const loading = ref(false)

const total = ref(0)
const queryForm = ref({
  query: '',
  pagenum: 1,
  pageSize: 10
})

const tableData = ref([])

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    0: 'warning', // 待确认
    1: 'primary', // 已确认
    2: 'success', // 已完成
    3: 'danger', // 咨询师拒绝
    4: 'warning', // 客户取消
    5: 'warning', // 咨询师取消
    6: 'info' // 已取消
  }
  return types[status] || 'info'
}

// 日期时间格式化
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('日期格式化失败:', error)
    return dateTimeStr
  }
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const labels = {
    0: '待确认',
    1: '已确认',
    2: '已完成',
    3: '咨询师拒绝',
    4: '客户取消',
    5: '咨询师取消',
    6: '已取消'
  }
  return labels[status] || '未知'
}

// 获取用户名字信息
const getUserNames = async (appointments) => {
  try {
    const counselorPromises = appointments.map(item =>
      item.counselor_id ? counselorApi.getCounselor({}, item.counselor_id) : null
    )
    const clientPromises = appointments.map(item =>
      item.client_id ? clientApi.getClientDetail(item.client_id) : null
    )

    const [counselorResults, clientResults] = await Promise.all([
      Promise.allSettled(counselorPromises),
      Promise.allSettled(clientPromises)
    ])

    return appointments.map((item, index) => {
      const counselorResult = counselorResults[index]
      const clientResult = clientResults[index]

      // 创建新对象而不是使用赋值
      return {
        ...item,
        client_name: clientResult?.value?.data?.[0]?.name || '未知客户',
        counselor_name: counselorResult?.value?.data?.[0]?.name || '未知咨询师'
      }
    })
  } catch (error) {
    console.error('获取用户名字失败:', error)
    return appointments
  }
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const { data } = await appointmentApi.getAppointment(queryForm.value)
    if (data) {
      if (Array.isArray(data)) {
        // 使用中间变量存储结果
        const appointmentsWithNames = await getUserNames(data)
        tableData.value = appointmentsWithNames
        total.value = data.length
      } else {
        ElMessage.error('获取预约列表失败')
      }
    } else {
      ElMessage.error(data?.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = async () => {
  try {
    if (queryForm.value.query) {
      // 先通过姓名查找客户
      const { data: clientData } = await clientApi.getClientList({
        name: queryForm.value.query
      })
      if (clientData) {
        // 找到客户，使用客户ID查询预约
        const clientId = clientData[0].user_id
        const { data } = await appointmentApi.getAppointment({
          client_id: clientId,
          query: '' // 清空query，因为已经用client_id查询
        })
        if (data) {
          if (Array.isArray(data)) {
            const appointmentsWithNames = await getUserNames(data)
            tableData.value = appointmentsWithNames
            total.value = data.length
          } else {
            ElMessage.error('获取预约列表失败')
          }
        }
      } else {
        // 未找到客户，清空列表
        tableData.value = []
        total.value = 0
        ElMessage.warning('未找到相关预约人')
      }
    } else {
      // 没有搜索条件，获取所有预约
      getList()
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  }
}

// 完成预约
const handleComplete = async (row) => {
  try {
    await ElMessageBox.confirm('确认完成该预约?', '提示', { type: 'warning' })
    const { data } = await appointmentApi.updateAppointment(row.record_id, {
      appointment_status: 2
    })
    if (data) {
      ElMessage.success('预约已完成')
      getList()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 取消预约
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确认取消该预约?', '提示', { type: 'warning' })
    const { data } = await appointmentApi.updateAppointment(row.record_id, {
      appointment_status: 6
    })
    if (data) {
      ElMessage.success('预约已取消')
      getList()
    }
  } catch (error) {
    console.error('取消失败:', error)
    ElMessage.error('取消失败')
  }
}
// 删除预约
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该预约记录?', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    const { data } = await appointmentApi.deleteAppointment(row.record_id)
    if (data) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(data?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 分页处理
const handleSizeChange = (size) => {
  queryForm.value.pagenum = 1
  queryForm.value.pageSize = size
  getList()
}

const handleCurrentChange = (page) => {
  queryForm.value.pagenum = page
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.header {
  padding: 16px;
  box-sizing: border-box;
}

:deep(.el-pagination) {
  margin-top: 16px;
  justify-content: center;
}

.el-tag {
  min-width: 65px;
  text-align: center;
}

:deep(.el-table) {
  .cell {
    white-space: nowrap;
  }
}
</style>
